<script setup>
import {userPageList, addUser} from "@/api/user";
import {ref, computed, onMounted} from "vue";
import { Plus } from '@element-plus/icons-vue'
import {useUserInfoStore} from "@/stores/userInfo";
import { logicDeleteUser } from "@/api/user";
console.log('logicDeleteUser类型:', typeof logicDeleteUser); // 应该是 'function'
const userInfoStore = useUserInfoStore();
import { ElMessageBox, ElMessage } from 'element-plus';
import { resetPassword } from "@/api/user";

const query = ref({
  pageNo: 1,
  pageSize: 10,
  mobile:'',
  balance:'',
  username: '',
  total: ''
})

const user = ref({
  username: '',
  password: '',
  avatar: ''
})

const imageUrl = ref('')

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  user.value.url = response.data.url
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('图片必须是 JPG/PNG/WEBP 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const users = ref([])
const getUserList = () => {
  userPageList(query.value).then(res => {
    users.value = res.data.records
    query.value.total = res.data.total
  })
}
getUserList()

const pageNoChange = (value) => {
  query.value.pageNo = value
  getUserList()
}

const pageSizeChange = (value) => {
  query.value.pageSize = value
  getUserList()
}

const dialogVisible = ref(false)
const showAddDialog = () => {
  // 重置表单和图片
  user.value = {
    username: '',
    password: '',
    avatar: ''
  }
  imageUrl.value = ''
  dialogVisible.value = true
}

const saveUser = () => {
  addUser(user.value).then(res => {
    if (res.data) {
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
      dialogVisible.value = false
      getUserList()
    }
  })
}

// 获取用户列表
onMounted(() => {
  getUserList();
});

// 格式化用户名显示
const formatUsername = (username) => {
  if (!username) return '';

  // 获取当前登录用户的备注
  const currentUserId = userInfoStore.userInfo?.id || '';

  // 如果是管理员用户，显示完整用户名
  if (currentUserId <= 3) {
    return username;
  }

  // 其他用户脱敏处理
  if (username.length <= 3) {
    return username.substring(0, 1) + '**';
  }

  // 显示前3位 + ***
  return username.substring(0, 3) + '***';
};

// 格式化密码显示
const formatPassword = (password) => {
  if (!password) return '';

  // 获取当前登录用户的备注
  const currentUserId = userInfoStore.userInfo?.id || '';

  // // 如果是管理员用户，显示完整密码（实际不建议）
  // if (currentUserId <= 3) {
  //   return password;
  // }

  // 其他用户显示固定长度的星号
  return '******';
}

const formatGender = (gender) => {
  switch(gender) {
    case 0: return '未设置';
    case 1: return '男';
    case 2: return '女';
    default: return '未知';
  }
}
const formatLevel = (levelId) => {
  switch(levelId) {
    case 1: return '银米';
    case 2: return '金米';
    case 3: return '白金米';
    case 4: return '钻石米';
    case 5: return '至尊钻石米';
    default: return '未知';
  }
}
const formatLevelDiscountRate = (levelId) => {
  switch (levelId) {
    case 1: return 1;
    case 2: return 0.98;
    case 3: return 0.95;
    case 4: return 0.9;
    case 5: return 0.85;
    default: return '未知';
  }
}
const formatLevelCanReturnWithoutReview = (levelId) => {
  switch (levelId) {
    case 1: return '不支持';
    case 2: return '不支持';
    case 3: return '不支持';
    case 4: return '支持（1000元以下）';
    case 5: return '支持（任意金额）';
    default: return '未知';
  }
}
const formatLevelPointsMultiplier = (levelId) => {
  switch (levelId) {
    case 1: return  '1.0x';
    case 2: return '1.2x';
    case 3: return '1.5x';
    case 4: return '2.0x';
    case 5: return '3.0x';
    default: return '未知';
  }
}


const removeUser = async (id) => {
  console.log("删除按钮被点击，用户ID:", id);
  try {
    await ElMessageBox.confirm('此操作将逻辑删除该用户，是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const res = await logicDeleteUser(id);
    console.log('删除接口返回:', res);

    if (res.data) {
      ElMessage.success('删除成功');
      getUserList();
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    console.log('删除catch错误:', error);
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};
const resetUserPassword = async (id) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户密码为默认值吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const res = await resetPassword(id);
    if (res.data) {
      ElMessage.success('密码已重置为默认值');
    } else {
      ElMessage.error('重置失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置失败');
    }
  }
}

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>用户列表</span>
      </div>
    </template>

    <div class="toolbar-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="query.username" placeholder="请输入用户名查询" clearable/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="query.mobile" placeholder="请输入手机号查询" clearable/>
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="query.balance" placeholder="查询余额小于输入值的用户" clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserList">查询</el-button>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="primary" @click="showAddDialog" class="add-button">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table :data="users" style="width: 100%" stripe border>
        <el-table-column prop="id" label="ID" width="60" align="center"/>
        <el-table-column prop="avatar" label="头像" width="120" align="center">
          <template #default="scope">
            <img v-if="scope.row.avatar" class="user-avatar" :src="scope.row.avatar" alt="">
            <span v-else>暂无头像</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ formatUsername(scope.row.username,scope.row.id) }}
          </template>
        </el-table-column>
        <el-table-column prop="password" label="手机号" width="120" align="center">
          <template #default="scope">
            {{ scope.row.mobile, scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            {{ formatGender(scope.row.gender) }}
          </template>
        </el-table-column>

        <el-table-column prop="levelId" label="会员等级" width="100" align="center">
          <template #default="scope">
            {{ formatLevel(scope.row.levelId) }}
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="120" align="right"/>
        <el-table-column prop="points" label="积分" width="120" align="right"/>
        <el-table-column prop="discountRate" label="购物折扣" width="100" align="center">
          <template #default="scope">
            {{ formatLevelDiscountRate(scope.row.levelId) }}
          </template>
        </el-table-column>
        <el-table-column prop="pointsMultiplier" label="积分倍率" width="100" align="center">
          <template #default="scope">
            {{ formatLevelPointsMultiplier(scope.row.levelId) }}
          </template>
        </el-table-column>
        <el-table-column prop="canReturnWithoutReview" label="退换货免审" width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ formatLevelCanReturnWithoutReview(scope.row.levelId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button-group>
              <el-button type="danger" size="small" @click="removeUser(scope.row.id)">
                删除
              </el-button>
              <el-button type="warning" size="small" @click="resetUserPassword(scope.row.id)">
                重置密码
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
          v-model:current-page="query.pageNo"
          v-model:page-size="query.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="query.total"
          @size-change="pageSizeChange"
          @current-change="pageNoChange"
      />
    </div>

    <!-- 添加用户弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="添加用户"
        width="500"
    >
      <el-form label-width="80px" style="max-width: 600px">
        <el-form-item label="用户名">
          <el-input v-model="user.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password" type="password" show-password placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">
.page-container {
  margin: 20px;
  min-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.toolbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.action-buttons {
  margin-left: auto;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.table-container {
  flex: 1;
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 4px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-button-group {
  display: flex;
  gap: 5px;
}

.el-button {
  margin: 0;
}
</style>

<style>
.el-table th.el-table__cell {
  background-color: #f5f7fa;
}
</style>
